package com.liuyubo.sort;

import java.util.Arrays;
import java.util.Random;

public class SortHelper {
    public static void main(String[] args) {
        //Sort sort1 = new SelectionSort();
        //Sort sort2 = new BubbleSort();
        //Sort sort3 = new InsertionSort();
        Sort sort4 = new MergeSort();
        Sort sort5 = new ShellSort();
        Sort sort6 = new MergeSortBU();
        Sort sort7 = new QuickSort();
        int[] arr0 = generateRandomArray(100000, 0, 100000);
        //int[] arr1 = copyArray(arr0);
        //int[] arr2 = copyArray(arr0);
        //int[] arr3 = copyArray(arr0);
        int[] arr4 = copyArray(arr0);
        int[] arr5 = copyArray(arr0);
        int[] arr6 = copyArray(arr0);
        int[] arr7 = copyArray(arr0);
        //testSort(sort1, arr1);
        //testSort(sort2, arr2);
        //testSort(sort3, arr3);
        testSort(sort4, arr4);
        testSort(sort5, arr5);
        testSort(sort6, arr6);
        testSort(sort7, arr7);
    }

    public static int[] generateRandomArray(int n, int rangeL, int rangeR) {
        assert rangeL < rangeR;
        int[] arr = new int[n];
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            arr[i] = random.nextInt(rangeR + 1 - rangeL) + rangeL;
        }
        return arr;
    }

    public static int[] generateNearlyOrderedArray(int n, int swapTimes) {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = i;
        }
        Random random = new Random();
        for (int i = 0; i < swapTimes; i++) {
            int posx = random.nextInt(n);
            int posy = random.nextInt(n);
            swap(arr, posx, posy);
        }
        return arr;
    }

    public static int[] copyArray(int[] arr) {
        int[] newArr = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            newArr[i] = arr[i];
        }
        return newArr;
    }

    public static void testSort(Sort sort, int[] arr) {
        long start = System.currentTimeMillis();
        sort.sort(arr);
        long end = System.currentTimeMillis();
        System.out.println(sort.getName() + ":" + (end - start) / 1000.0 + " s");
        assert isOrdered(arr);
    }

    public static boolean isOrdered(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                return false;
            }
        }
        return true;
    }

    private static void swap(int[] arr, int posi, int posj) {
        int temp = arr[posi];
        arr[posi] = arr[posj];
        arr[posj] = temp;
    }
}
